package Pakke;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.sound.sampled.*;

/**
 *
 * FancyTimerSound.java
 *
 * @author arni
 *
 * Spiller av lyd i loop til tråden blir drept.
 *
 *  ref: http://onjava.com/pub/a/onjava/2004/08/11/javasound-mp3.html?page=1
 *
 */
public class FancyTimerSound  implements Runnable {

    private SourceDataLine line;
    private AudioInputStream din = null;
    private byte[] data;
    private AudioInputStream in;
    private AudioFormat decodedFormat;
    private File file;
    private URL url;
    private URI uri;
    private URI defaultlyd;
    private boolean notStopped = true;

    /**
     * Tar en String med stien til lydfila (mp3) som argument, og setter opp en
     * audiostream for fila. Hvis filtypen ikke støttes returneres en melding om dette.
     * @param path
     */
    public FancyTimerSound(String path) {
        try {
            defaultlyd = getClass().getResource("sound/moredots.mp3").toURI();
        } catch (URISyntaxException ex) {
        }
    file = new File(path);
    if(!file.isFile()) {
        // Fila finnes ikke, bruk defaultfil.
        uri = defaultlyd;
       System.out.println("Fant ikke fila: " + path + " bruker default");
       // System.out.println(path);
    }
    else{ 
        // Fant fila
        System.out.println("Fant fila " + path);
        uri = file.toURI();
      //  System.out.println(uri.toASCIIString());
    }

               // uri = defaultlyd;
    try {
        in = AudioSystem.getAudioInputStream(uri.toURL());
    } catch (IOException ex) {ex.printStackTrace();
    } catch (UnsupportedAudioFileException ex) {
        System.out.println("Får ikke spilt av fila");
        ex.printStackTrace();
    }

    
    din = null;
    AudioFormat baseFormat = in.getFormat();
    decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                        baseFormat.getSampleRate(),
                        16,
                        baseFormat.getChannels(),
                        baseFormat.getChannels() * 2,
                        baseFormat.getSampleRate(),
                        false);
        try {
            // Play now.
            rawplay(decodedFormat);
            //din = AudioSystem.getAudioInputStream(decodedFormat, in);
            //in.close();
        } catch (IOException ex) {
        } catch (LineUnavailableException ex) {
        }
    }

    /**
     * 
     * @param targetFormat
     * @throws IOException
     * @throws LineUnavailableException
     */
    private void rawplay(AudioFormat targetFormat) throws IOException, LineUnavailableException {
        data = new byte[4096];
        line = getLine(targetFormat);
    }

    /**
     * 
     * @param audioFormat
     * @return
     * @throws LineUnavailableException
     */
    private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info =  new DataLine.Info(SourceDataLine.class, audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    /**
     * Run-metoden for å spille av mp3-fila.
     */
    @SuppressWarnings("empty-statement")
    public void run() {
    while (notStopped) {
    try {
    in = AudioSystem.getAudioInputStream(uri.toURL());
    } catch (Exception e) {};
    din = AudioSystem.getAudioInputStream(decodedFormat, in);
    try {
      if (line != null) {
        line.start();
        int nBytesRead = 0, nBytesWritten = 0;
        while (nBytesRead != -1) {
          nBytesRead = din.read(data, 0, data.length);
          if (nBytesRead != -1)
            nBytesWritten = line.write(data, 0, nBytesRead);
          }
        line.drain();
        line.stop();
        }
      } catch (Exception e) {}
    }}

    /**
     * Metode for å stoppe lydavspillingen.
     */
    public void stopSound() {
    // Stop
        notStopped = false;
      //  line.drain();


        try {
        line.stop();
        line.close();
        in.close();
        din.close();
        } catch (Exception e) {}
    }

}
